package xcmg.device.service.company;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Font;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xcmg.device.infra.CellMergeParam;
import xcmg.device.service.vo.agent.ServiceBasicDataAgentVO;
import xcmg.device.service.vo.company.EmployeeSettingResultVO;
import xcmg.device.service.vo.company.EmployeeSettingVO;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * EmployeeSetting exel相关
 */
@Service
public class EmployeeSettingExcelService {


    private static final Logger logger = LoggerFactory.getLogger(EmployeeSettingExcelService.class);

    @Autowired
    private HttpServletResponse response;

    public void exportRpt(EmployeeSettingResultVO vo) throws IOException {

        String title = "人员配置标准";
        String sheetName = "人员配置标准";
        setHttpResponse(response, title);
        OutputStream outputStream = response.getOutputStream();
        ExcelWriter writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLSX, true);

        List<List<String>> names = new ArrayList<>();
        List<CellMergeParam> cellMergeParams = new ArrayList<>();
        List<String> h1 = new ArrayList<>();
        h1.add("序号");
        CellMergeParam cellMergeParam = new CellMergeParam(0, 1, 0, 0);
        cellMergeParams.add(cellMergeParam);
        names.add(h1);
        List<String> h2 = new ArrayList<>();
        h2.add("代理商");
        CellMergeParam cellMergeParam2 = new CellMergeParam(0, 1, 1, 1);
        cellMergeParams.add(cellMergeParam2);
        names.add(h2);

        List<String> h3 = new ArrayList<>();
        h3.add("小计");
        h3.add("标准");
        names.add(h3);

        List<String> h4 = new ArrayList<>();
        h4.add("小计");
        h4.add("配置");
        names.add(h4);

        List<String> h5 = new ArrayList<>();
        h5.add("小计");
        h5.add("缺编");
        names.add(h5);

        List<String> h6 = new ArrayList<>();
        h6.add("小计");
        h6.add("配置率");
        names.add(h6);

        int nCol = 5;
        for (ServiceBasicDataAgentVO jb : vo.getJobs()) {
            List<String> h7 = new ArrayList<>();
            h7.add(jb.getName());
            h7.add("标准");
            names.add(h7);
            List<String> h8 = new ArrayList<>();
            h8.add(jb.getName());
            h8.add("配置");
            names.add(h8);
            List<String> h9 = new ArrayList<>();
            h9.add(jb.getName());
            h9.add("缺编");
            names.add(h9);
            List<String> h10 = new ArrayList<>();
            h10.add(jb.getName());
            h10.add("配置率");
            names.add(h10);
            nCol = nCol + 4;
        }
        // 写第一个sheet, sheet1  数据全是List<String> 无模型映射关系
        Sheet sheet1 = new Sheet(1, 0);
        sheet1.setSheetName(sheetName);
        sheet1.setHead(names);
        List<List<Object>> writeList = genWriteList(vo, names);
        Font heardfont = new Font();
        heardfont.setFontHeightInPoints((short) 12);
        heardfont.setBold(true);

        Font contentfont = new Font();
        contentfont.setFontHeightInPoints((short) 10);
        contentfont.setBold(false);

        TableStyle tableStyle = new TableStyle();
        tableStyle.setTableHeadFont(heardfont);
        tableStyle.setTableHeadBackGroundColor(IndexedColors.WHITE);
        tableStyle.setTableContentBackGroundColor(IndexedColors.WHITE);
        tableStyle.setTableContentFont(contentfont);
        sheet1.setTableStyle(tableStyle);
        writer.write1(writeList, sheet1);
        cellMerge(cellMergeParams, writer);
        writer.finish();
    }

    private List<List<Object>> genWriteList(EmployeeSettingResultVO vo, List<List<String>> names) {
        List<List<Object>> writeList = new ArrayList<>();
        int i = 1;
        for (List<EmployeeSettingVO> list : vo.getEmployeeSettingVOs().getList()) {
            i = getRowObjectList(writeList, i, list);
        }
        return writeList;
    }

    private int getRowObjectList(List<List<Object>> writeList, int i, List<EmployeeSettingVO> list) {
        DecimalFormat df = new DecimalFormat("0.00%");
        List<Object> row = new ArrayList<>();
        int numberEmpRealRow = 0;
        int numberEmpNeedRow = 0;
        int numberEmpRow = 0;
        String jobRateRow = "";
        String orgName = null;
        for (EmployeeSettingVO vvo : list) {
            orgName = vvo.getOrgName();
            if (null == vvo.getNumberEmpReal()) {
                vvo.setNumberEmpReal(0);
            }
            if (null == vvo.getNumberEmp()) {
                vvo.setNumberEmp(0);
            }
            if (null == vvo.getNumberEmpNeed()) {
                vvo.setNumberEmpNeed(0);
            }

            numberEmpRealRow = numberEmpRealRow + vvo.getNumberEmpReal();
            numberEmpNeedRow = numberEmpNeedRow + vvo.getNumberEmpNeed();
            numberEmpRow = numberEmpRow + vvo.getNumberEmp();
            if (vvo.getNumberEmp() > 0) {
                BigDecimal rate = BigDecimal.valueOf(vvo.getNumberEmpReal()).divide(BigDecimal.valueOf(vvo.getNumberEmp()), 4);
                vvo.setJobRate(df.format(rate));
            }
        }
        if (numberEmpRow > 0) {
            BigDecimal rate = BigDecimal.valueOf(numberEmpRealRow).divide(BigDecimal.valueOf(numberEmpRow), 4);
            jobRateRow = df.format(rate);
        }
        row.add(i);
        row.add(orgName);
        row.add(numberEmpRow);
        row.add(numberEmpRealRow);
        row.add(numberEmpNeedRow);
        row.add(jobRateRow);
        for (EmployeeSettingVO vvo : list) {
            row.add(vvo.getNumberEmp());
            row.add(vvo.getNumberEmpReal());
            row.add(vvo.getNumberEmpNeed());
            row.add(vvo.getJobRate());
        }
        writeList.add(row);
        return ++i;
    }


    /**
     * 合并单元格
     *
     * @param cellMergeParams
     * @param writer
     * @author wangyong
     */
    private void cellMerge(List<CellMergeParam> cellMergeParams, ExcelWriter writer) {
        if (CollectionUtils.isEmpty(cellMergeParams)) {
            return;
        }
        for (CellMergeParam mergeParam : cellMergeParams) {
            writer.merge(mergeParam.getFirstRow(), mergeParam.getLastRow(),
                    mergeParam.getFirstCol(), mergeParam.getLastCol());
        }
    }

    private void setHttpResponse(HttpServletResponse response, String title) throws UnsupportedEncodingException {
        Format format = new SimpleDateFormat("yyyyMMdd");
        String fileName = "Excel-" + format.format(new Date()) + title;
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso8859-1") + ".xlsx");
        response.setContentType("application/x-msdownload");
    }
}
